package ar.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ar.Location.Constant.Define;
import ar.Location.Helper.BitmapProvider;
import ar.Location.Map.EnhancedMapView;
import ar.Location.Map.MyOverlayItem;
import ar.Location.Map.SharingLocations;
import ar.activity.R.string;
import ar.camera.pojo.GeoLocation;
import ar.camera.thread.ConnectServerThread;
import ar.camera.thread.MainClientThread;
import ar.globals.Globals;
import ar.sms.SMSSender;
import ar.sql.RouteDatabaseHandler;
import ar.view.adapter.ShareAdapter;
import arserver.pojo.RegistrationItem;

import com.google.android.maps.GeoPoint;

public class ShareActivity extends BaseActivity {

	public static final int GET_CONTACTS = 1;
	public static final int CHOOSE_FRIEND = 2;
	protected static final String TAG = "ShareActivity";
	private ListView lvShare;
	private Thread background1;
	private Thread background2;
	private boolean isTracking = false;
	private ProgressDialog pbarDialog;
	private ShareAdapter shareAdapter;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Globals.MSG_CONNECT_SUCCESSFULLY:
				pbarDialog.dismiss();
				Toast.makeText(getApplicationContext(),
						res.getString(string.shareMenu4), Toast.LENGTH_SHORT)
						.show();
				Globals.isEnable1 = false;
				Globals.isEnable2 = true;
				Globals.isEnable3 = true;
				Globals.isEnable4 = true;
				enableOrDisableListItems();

				break;
			case Globals.MSG_CONNECT_FAILED:
				String error = (String) msg.obj;
				pbarDialog.dismiss();
				Toast.makeText(getApplicationContext(), error,
						Toast.LENGTH_SHORT).show();
				break;
			case Globals.MSG_GET_STRING:
				String networkInfo = (String) msg.obj;
				Toast.makeText(getApplicationContext(), networkInfo,
						Toast.LENGTH_SHORT).show();
				break;
			case Globals.MSG_GET_REGISTRATION_LIST:
				@SuppressWarnings("unchecked")
				ArrayList<RegistrationItem> items = (ArrayList<RegistrationItem>) msg.obj;
				List<String> srcNames = new ArrayList<String>();
				List<String> srcNumbers = new ArrayList<String>();
				for (RegistrationItem i : items) {
					srcNames.add(i.getSrcName());
					srcNumbers.add(i.getSrcPhoneNumber());
				}
				if (srcNames.size() > 0) {
					Intent i = new Intent(getApplicationContext(),
							ShareChooseFriendActitvity.class);
					i.putStringArrayListExtra("srcNames",
							(ArrayList<String>) srcNames);
					i.putStringArrayListExtra("srcNumbers",
							(ArrayList<String>) srcNumbers);
					startActivityForResult(i, CHOOSE_FRIEND);
				} else {
					Toast.makeText(getApplicationContext(),
							res.getString(string.shareNoOne),
							Toast.LENGTH_SHORT).show();
				}
				break;
			case Globals.MSG_GET_REGISTRATION_ITEM:
				RegistrationItem value = (RegistrationItem) msg.obj;
				Globals.routePoints.add(value);
				// Toast.makeText(getApplicationContext(),
				// value.getLat() + " " + value.getLng(),
				// Toast.LENGTH_SHORT).show();
				if (isTracking) {
					if (!value.getLat().equals("")
							&& !value.getLng().equals("")) {
						GeoLocation friendLocation = new GeoLocation(
								Float.valueOf(value.getLat()),
								Float.valueOf(value.getLng()),
								value.getSrcName());

						// Tracking on camera
						if (Globals.isTrackingOnCam) {
							Globals.listOfGeoLocations = new ArrayList<GeoLocation>();
							Globals.listOfGeoLocations.add(friendLocation);
							if (Globals.locationIconView != null)
								Globals.locationIconView.getmRenderer()
										.setmListOfGeoLocations(
												Globals.listOfGeoLocations);
							if (Globals.compassView != null)
								Globals.compassView.getmRenderer()
										.setmListOfGeoLocations(
												Globals.listOfGeoLocations);

							SharingLocations.listSharingsOnCam = new ArrayList<MyOverlayItem>();
							int lt = (int) (Float.valueOf(value.getLat()) * 1E6);
							int lg = (int) (Float.valueOf(value.getLng()) * 1E6);

							GeoPoint point = new GeoPoint(lt, lg);
							MyOverlayItem myOverlay = new MyOverlayItem(point,
									value.getSrcName(),
									value.getSrcPhoneNumber());
							SharingLocations.listSharingsOnCam.add(myOverlay);

							break;
						}

						SharingLocations.listSharingsOnCam.clear();

						// Me
						GeoPoint mPoint = Globals.getMyLocation();
						if (mPoint != null) {

							MyOverlayItem me = new MyOverlayItem(mPoint, "Me",
									value.getDesPhoneNumber());
							me.setMarker(BitmapProvider.trackingMe);
							SharingLocations.listSharingsOnCam.add(me);
						}

						// Friend
						GeoPoint fPoint = new GeoPoint(
								(int) (friendLocation.getLatitude() * 1E6),
								(int) (friendLocation.getLongitude() * 1E6));
						MyOverlayItem friend = new MyOverlayItem(fPoint,
								value.getSrcName(), value.getSrcPhoneNumber());
						friend.setMarker(BitmapProvider.trackingFriend);
						SharingLocations.listSharingsOnCam.add(friend);

						if (EnhancedMapView.MODE_TRACKING_ON_MAP) {
							if (ARMapActivity.handleShareLocation != null) {
								ARMapActivity.handleShareLocation
										.sendEmptyMessage(0);
							}
						}
					}

				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.share);
		super.onCreate(savedInstanceState);
		tvWhatScreen.setText(res.getString(string.shareScreenName));

		getShareInformation();

		lvShare = (ListView) findViewById(R.id.lvShare);
		shareAdapter = new ShareAdapter(this);
		lvShare.setAdapter(shareAdapter);
		initEventClick();
	}

	public void initEventClick() {
		lvShare.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				switch (position) {
				case 0:// connect
					if (Globals.isEnable1) {
						pbarDialog = ProgressDialog.show(ShareActivity.this,
								res.getString(string.shareConnecting),
								res.getString(string.shareWait));
						connectToServer();
					}
					break;
				case 1:// share
					if (Globals.isEnable2) {
						pickContacts();
					}
					break;
				case 2:// choose friend for tracking
					if (Globals.isEnable3) {
						getGetTrackCode();
						// getFriendLocation();
						// Globals.isEnable3 = false;
						// Globals.isEnable31_32 = true;
						// isTracking = true;
					}
					break;
				case 3:// open map
					if (Globals.isEnable31_32) {
						EnhancedMapView.MODE_TRACKING_ON_MAP = true;
						Intent intent = new Intent(ShareActivity.this,
								ARMapActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra(Define.ACTION_OUTSIDE_MAP,
								Define.ACTION_TRACKING_ON_MAP);
						startActivity(intent);
					}
					break;
				case 4:// open camera
					if (Globals.isEnable31_32) {
						Globals.isTrackingOnCam = true;
						Globals.listOfGeoLocations = new ArrayList<GeoLocation>();
						if (Globals.locationIconView != null)
							Globals.locationIconView.getmRenderer()
									.setmListOfGeoLocations(
											Globals.listOfGeoLocations);
						if (Globals.compassView != null)
							Globals.compassView.getmRenderer()
									.setmListOfGeoLocations(
											Globals.listOfGeoLocations);
						Intent i = new Intent(getApplicationContext(),
								ARCameraActivity.class);
						startActivity(i);
					}
					break;
				case 5:// disconnect
					if (Globals.isEnable4) {
						writeRouteDatabase();
						if (disConnectToServer()) {
							Globals.isEnable1 = true;
							Globals.isEnable2 = false;
							Globals.isEnable3 = false;
							Globals.isEnable31_32 = false;
							Globals.isEnable4 = false;
						}
					}
					break;
				case 6:// Load routes
					if (Globals.isEnable1) {
						Intent i = new Intent(getApplicationContext(),
								LoadRoutesActivity.class);
						startActivity(i);
					}
					break;
				default:
					break;
				}
				enableOrDisableListItems();
			}
		});
	}

	private void writeRouteDatabase() {
		if (isTracking && Globals.routePoints != null
				&& Globals.routePoints.size() > 0) {

			final RouteDatabaseHandler myDbHelper = new RouteDatabaseHandler(
					this);
			try {
				myDbHelper.openDataBase();
			} catch (SQLException sqle) {
				throw sqle;
			}

			AlertDialog.Builder infoDlg = new Builder(this);
			infoDlg.setTitle(res.getString(string.shareImportantNote));

			LayoutInflater inflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.share_get_route_description,
					null, false);
			infoDlg.setView(view);
			final EditText etRouteDesc = (EditText) view
					.findViewById(R.id.etRouteDesc);
			etRouteDesc.setText("example...");

			infoDlg.setPositiveButton(res.getString(string.OK),
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Globals.routeDesc = etRouteDesc.getText()
									.toString();
							Thread t = new Thread(new Runnable() {

								@Override
								public void run() {
									if (Globals.routePoints != null) {
										synchronized (Globals.routePoints) {
											for (RegistrationItem item : Globals.routePoints) {
												myDbHelper.add(item);
											}
										}
									}
									Globals.routePoints = new ArrayList<RegistrationItem>();
								}
							});
							t.start();
							Toast.makeText(getBaseContext(), "Saved",
									Toast.LENGTH_LONG).show();
						}
					});
			infoDlg.setNegativeButton(res.getString(string.Cancel),
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// Do nothing...
						}
					});
			infoDlg.show();
			myDbHelper.close();
		}
	}

	private void getFriendLocation() {
		if (Globals.mainClient2Thread != null) {
			Globals.mainClient2Thread.disConnect();
			Globals.mainClient2Thread = null;
		}
		Globals.mainClient2Thread = new MainClientThread(Globals.client2Socket,
				handler, false, true);
		stopThread(background2);
		background2 = new Thread(Globals.mainClient2Thread);
		background2.start();
	}

	public void stopThread(Thread t) {
		if (t == null)
			return;
		Thread tmp = t;
		t = null;
		tmp.interrupt();
	}

	private void pickContacts() {
		Intent i = new Intent(this, ShareGetContactsActitvity.class);
		startActivityForResult(i, GET_CONTACTS);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (GET_CONTACTS):
			if (resultCode == Activity.RESULT_OK) {
				String[] numbers = data.getStringArrayExtra("numberArray");
				Globals.phoneNumbersOfSharedFriends = Arrays.asList(numbers);
				SMSSender smsSender = new SMSSender(this);
				if (Globals.isNeedSendMessage) {
					for (String str : Globals.phoneNumbersOfSharedFriends) {
						smsSender.sendSMS(str, "ARLocation:"
								+ Globals.shareCode);
					}
				}
				registerAndShare(numbers);
				Globals.isEnable2 = false;
				Globals.isSharingLocation = true;
				enableOrDisableListItems();
				Toast.makeText(getBaseContext(),
						res.getString(string.shareNow), Toast.LENGTH_SHORT)
						.show();
			}
			break;
		case (CHOOSE_FRIEND):
			if (resultCode == Activity.RESULT_OK) {
				String number = data.getStringExtra("number");
				String name = data.getStringExtra("name");
				Globals.phoneNumberOfSharingFriend = number;
				Globals.isEnable3 = false;
				Globals.isEnable31_32 = true;

				Toast.makeText(getApplicationContext(), name + " - " + number,
						Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}

	public void connectToServer() {
		ConnectServerThread connServer = new ConnectServerThread(handler);
		Thread t = new Thread(connServer);
		t.start();
	}

	private boolean disConnectToServer() {
		boolean r1 = true;
		boolean r2 = true;
		if (Globals.mainClient1Thread != null) {
			r1 = Globals.mainClient1Thread.disConnect();
			try {
				Globals.client1Socket.close();
				Globals.client1Socket = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (Globals.mainClient2Thread != null) {
			r2 = Globals.mainClient2Thread.disConnect();
			try {
				Globals.client2Socket.close();
				Globals.client2Socket = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return r1 && r2;
	}

	public void registerAndShare(String[] numbers) {
		Globals.mainClient1Thread = new MainClientThread(Globals.client1Socket,
				handler, true, false);
		Globals.mainClient1Thread.setDes(numbers);
		stopThread(background1);
		background1 = new Thread(Globals.mainClient1Thread);
		background1.start();
	}

	private void getShareInformation() {
		AlertDialog.Builder infoDlg = new Builder(this);
		infoDlg.setTitle(res.getString(string.shareImportantNote));

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.share_get_information, null,
				false);
		infoDlg.setView(view);
		final EditText etNumber = (EditText) view
				.findViewById(R.id.etShareNumber);
		etNumber.setText(Globals.phoneNumber);
		final EditText etNickName = (EditText) view
				.findViewById(R.id.etShareNickName);
		etNickName.setText(Globals.nickName);

		infoDlg.setPositiveButton(res.getString(string.OK),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Globals.phoneNumber = etNumber.getText().toString();
						Globals.nickName = etNickName.getText().toString();
						if (Globals.phoneNumber.trim().equals("")
								|| Globals.nickName.trim().equals("")) {
							Toast.makeText(getApplicationContext(),
									res.getString(string.shareEnterAll),
									Toast.LENGTH_SHORT).show();
							finish();
						}
					}
				});

		infoDlg.setNegativeButton(res.getString(string.Cancel),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (Globals.phoneNumber.trim().equals("")
								|| Globals.nickName.trim().equals("")) {
							Toast.makeText(getApplicationContext(),
									res.getString(string.shareEnterAll),
									Toast.LENGTH_SHORT).show();
							finish();
						}
					}
				});
		infoDlg.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (Globals.phoneNumber.trim().equals("")
						|| Globals.nickName.trim().equals("")) {
					Toast.makeText(getApplicationContext(),
							res.getString(string.shareEnterAll),
							Toast.LENGTH_SHORT).show();
					finish();
				}
			}
		});
		infoDlg.show();
	}

	private void getGetTrackCode() {
		AlertDialog.Builder infoDlg = new Builder(this);
		infoDlg.setTitle(res.getString(string.shareImportantNote));

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.share_track_code, null, false);
		infoDlg.setView(view);
		final EditText etTrackCode = (EditText) view
				.findViewById(R.id.etShareTrackCode);
		etTrackCode.setText(Globals.trackCode);

		infoDlg.setPositiveButton(res.getString(string.OK),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Globals.trackCode = etTrackCode.getText().toString();
						Toast.makeText(getApplicationContext(),
								"Code: " + Globals.trackCode,
								Toast.LENGTH_SHORT).show();
						getFriendLocation();
						Globals.isEnable3 = false;
						Globals.isEnable31_32 = true;
						isTracking = true;
					}
				});
		infoDlg.show();
	}

	public void enableOrDisableListItems() {
		View item = null;
		TextView tvMain;
		TextView tvSub;

		int firstPos = lvShare.getFirstVisiblePosition()
				- lvShare.getHeaderViewsCount();

		int wantedPos = 0 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable1) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
		wantedPos = 1 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable2) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
		wantedPos = 2 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable3) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
		wantedPos = 3 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable31_32) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
		wantedPos = 4 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable31_32) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
		wantedPos = 5 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable4) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
		wantedPos = 6 - firstPos;
		if (wantedPos >= 0 && wantedPos < lvShare.getChildCount()) {
			item = lvShare.getChildAt(wantedPos);
			tvMain = (TextView) item.findViewById(R.id.tvShareMain);
			tvSub = (TextView) item.findViewById(R.id.tvShareSub);
			if (Globals.isEnable1) {
				enableViews(tvMain, tvSub, item);
			} else {
				disableViews(tvMain, tvSub, item);
			}
		}
	}

	public void disableViews(TextView tvMain, TextView tvSub, View item) {
		tvMain.setTextColor(Color.GRAY);
		tvSub.setTextColor(Color.GRAY);
	}

	public void enableViews(TextView tvMain, TextView tvSub, View item) {
		tvMain.setTextColor(Color.WHITE);
		tvSub.setTextColor(Color.parseColor("#08c5a9"));
	}

	@Override
	protected void onUpdateUI() {
		// TODO Auto-generated method stub
		tvWhatScreen.setText(res.getString(string.shareScreenName));
		setContentView(R.layout.share);
		lvShare = (ListView) findViewById(R.id.lvShare);
		lvShare.setAdapter(shareAdapter);
		initEventClick();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}
}
